/*excel等文件流的下载*/

import axios from 'axios'
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: "http://localhost:9093/blog/",
  // 超时
  timeout: 10000
});

// request拦截器
service.interceptors.request.use(
  config => {
    //添加token,
    config.headers['Authorization'] = window.localStorage.getItem("token"); // 让每个请求携带自定义token 请根据实际情况自行修改
    //获取token
    return config
  },
  error => {
    console.log(error);
    Promise.reject(error)
  }
);


//拦截响应直接下载文件
service.interceptors.response.use(res => {
    let blob = new Blob([res.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'});
    let url = window.URL.createObjectURL(blob);
    let aLink = document.createElement("a");
    aLink.style.display = "none";
    aLink.href = url;
    //获取文件名称
    let name = res.headers['content-disposition'];
    let filename = name.split("=")[1];
    aLink.setAttribute("download", filename);
    document.body.appendChild(aLink);
    aLink.click();
    document.body.removeChild(aLink); //下载完成移除元素
    window.URL.revokeObjectURL(url); //释放掉blob对象
    return res;
  },
  error => {
    console.log('err' + error);
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error)
  }
);

export default service
